package com.xuyuan.experssion.mvel;

import lombok.Data;
import org.junit.jupiter.api.Test;
import org.mvel2.MVEL;
import org.mvel2.compiler.ExecutableAccessor;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

public class MVELExam {
    @Test
    public void test() {
        Person personInst = new Person();
        personInst.setName("Mr.Foo");
        // 判断相等
        Boolean objResult = MVEL.evalToBoolean("name == 'Mr.Foo'", personInst);
        System.out.println("objResult=" + objResult);

        // 取值
        String strResult = MVEL.evalToString("name", personInst);
        System.out.println("strResult=" + strResult);

        // 计算
        Map vars = new HashMap();
        vars.put("x", new Integer(5));
        vars.put("y", new Integer(10));

        // 第一种方式
        Integer intResult = (Integer) MVEL.eval("x * y", vars);
        System.out.println("intResult=" + intResult);
        // 第二种方式
        ExecutableAccessor compiled = (ExecutableAccessor) MVEL.compileExpression("x * y");
        intResult = (Integer) MVEL.executeExpression(compiled, vars);
        System.out.println("intResult=" + intResult);

    }

    @Test
    public void test2() {
        String expression = "foobar > 99";
        Map vars = new HashMap();
        vars.put("foobar", new Integer(100));
        Boolean result = MVEL.evalToBoolean(expression, vars);
        if (result) {
            System.out.println("It works!");
        }
    }

    /**
     * 在 Java 中计算字符串数值表达式可以用 javax.script.ScriptEngine#eval(java.lang.String)，通过调用 JavaScript 来计算
     */
    @Test
    public void test3() {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
        String expression = "10 * 2 + 6 / (3 - 1)";
        try {
            String result = String.valueOf(scriptEngine.eval(expression));
            System.out.println(result);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    @Data
    class Person {
        private String name;
    }
}
